package com.jiuyi.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiuyi.common.R;
import com.jiuyi.dto.StatusIdDto;
import com.jiuyi.entity.*;
import com.jiuyi.mapper.*;

import com.jiuyi.service.OrderDetailService;
import com.jiuyi.service.OrdersService;
import com.jiuyi.utils.BeanCopyUtils;
import com.jiuyi.vo.OrdersVo;
import com.jiuyi.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;



/**
 * DATA: 2022/10/24
 * Author: 晨夕
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {


    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailServiceImpl orderDetailServiceImpl;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;


    //去支付
    @Override
    @Transactional
    public R submit(Orders orders, HttpServletRequest request) {
        //1. 获取当前用户id
        Object userId = request.getSession().getAttribute("user");
        //2. 查询当前用户的购物车数据
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectByUserId(Long.parseLong(userId.toString()));
        //3. 向详细订单表中插入数据，多条，批量插入
        List<OrderDetail> orderDetails = BeanCopyUtils.copyBeanList(shoppingCarts, OrderDetail.class);
        //3.1 订单号随机生成
        Long orderId = IdWorker.getId();
        for(OrderDetail orderDetail : orderDetails){
            orderDetail.setOrderId(orderId);
        }
        orderDetailServiceImpl.saveBatch(orderDetails);
        //4. 向订单表中插入数据，一条
        //4.1 根据userId查询地址id
        LambdaQueryWrapper<AddressBook> query = new LambdaQueryWrapper<>();
        query.eq(AddressBook::getUserId,Long.parseLong(userId.toString()));
        query.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookMapper.selectOne(query);
        String detail = addressBook.getDetail();
        //4.2 根据 userId查找userName
        User user = userMapper.selectById(Long.parseLong(userId.toString()));
        // 4.3 遍历详细订单表，计算总金额
        AtomicInteger counter = new AtomicInteger(0);
        for(OrderDetail orderDetail : orderDetails){
            String amount = String.valueOf(orderDetail.getAmount());
            String number = Double.toString(orderDetail.getNumber());
            BigDecimal bigDecimal = new BigDecimal(number);
            BigDecimal multiply = new BigDecimal(amount).multiply(bigDecimal);
            counter.addAndGet(multiply.intValue());
        }
        //4.4 插入数据
        orders.setNumber(orderId.toString());
        orders.setStatus(2);
        orders.setUserId(Long.parseLong(userId.toString()));
        orders.setAddressBookId(addressBook.getId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(Double.parseDouble(new BigDecimal(counter.get()).toString()));
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(detail);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        //4.5插入到数据库中
        ordersMapper.insert(orders);
        //5. 清空购物车订单
        //根据id删除订单
        LambdaQueryWrapper<ShoppingCart> shoppingCartQuery = new LambdaQueryWrapper<>();
        shoppingCartQuery.eq(ShoppingCart::getUserId,Long.parseLong(userId.toString()));
        shoppingCartMapper.delete(shoppingCartQuery);
        return R.success("下单成功");
    }

    //查看历史订单
    @Override
    public R selectPage(int page, int pageSize) {
        List<Orders> orders = ordersMapper.selectByPage(page, pageSize);
        PageVo<Orders> pageVo = new PageVo<>();
        pageVo.setRecords(orders);
        return R.ok(pageVo);
    }
    //后台订单明细
    @Override
    public R<OrdersVo> selectByPages(int page, int pageSize, String number, LocalDateTime orderTime, LocalDateTime checkoutTime) {
        List<Orders> orders = ordersMapper.selectByPages((page-1) * pageSize, pageSize, number, orderTime, checkoutTime);
        int count = ordersMapper.selectByPageCount(number, orderTime, checkoutTime);
        //根据每一单的user_id查询用户名
        List<OrdersVo> ordersVos = BeanCopyUtils.copyBeanList(orders, OrdersVo.class);
        for(OrdersVo ordersVo : ordersVos){
            String name = userMapper.selectNameById(ordersVo.getUserId());
            ordersVo.setName(name);
        }
        PageVo<OrdersVo> pageVo = new PageVo<>();
        pageVo.setRecords(ordersVos);
        pageVo.setTotal(count);
        return R.ok(pageVo);
    }
    //修改派送状态
    @Override
    public R updatePayMethod(StatusIdDto statusIdDto) {
        ordersMapper.updateStatusById(statusIdDto.getStatus(),Long.parseLong(statusIdDto.getId()));
        return R.success("已派送");
    }
}
